//
//  AssignConfirmViewController.m
//  CloudMD
//
//  Created by centling on 16/4/20.
//  Copyright © 2016年 HuaZhengInfo. All rights reserved.
//

#import "AssignConfirmViewController.h"
#import "ZLPhotoPickerViewController.h"
#import "ZLPhotoAssets.h"
#import "GYLAddImage.h"
#import "ImposeUserInfoModel.h"
#import "GrabOrderViewController.h"

@interface AssignConfirmViewController ()<UITableViewDataSource,UITableViewDelegate,UIActionSheetDelegate,UIAlertViewDelegate>{
    
    UIView * _mainView;
    UIImageView * _view1;
    UIImageView * _view2;
    UILabel * _roomLabel; // 区位
    UIButton * _cateButton; // 类型
    
    UITableView * _roomTableView; // 区位列表
    
    UIButton *_grabBtn;
    
    NSMutableArray * _roomArray;
    NSMutableArray * _cateArray;
    NSMutableArray * _dataArray;
    NSString * _state; // 状态
    NSString * _ID; // ID
    
    BOOL roomShow;
    BOOL cateShow;
}
@property (nonatomic, strong) UIDatePicker *datePicker;
@property (nonatomic, copy) NSString *selectedUserId;
@property (nonatomic, copy) NSString *selectedUserCode;
@property (nonatomic, copy) NSString *selectDateStr;

@end



@implementation AssignConfirmViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    // 导航栏左按钮
    UIButton * leftButton = [GDFactory creatUIButtonWithFrame:CGRectMake(0, 0, 10, 15) backImage:@"left_arrow" title:nil titleLableColcor:nil titleLabelFont:nil];
    [leftButton addTarget:self action:@selector(clickLeft) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    self.title = @"订单指派";
    
    // 初始化
    _cateArray = [NSMutableArray array];
    _roomArray = [NSMutableArray array];
    _dataArray = [NSMutableArray array];
    _state = @"SUCCESS";
    _ID = [[NSString alloc] init];
    roomShow = NO;
    cateShow = NO;
    [self buildMainUI];
    
    //  请求区位数据
    [self requestWGHData];
    
    //  请求订单类型数据
    
    //  我要下单数据操作
    //    [self orderSendData];
}


#pragma mark -- 创建UI
- (void)buildMainUI{
    
    //    _mainView = [GDFactory creatUIViewWithFrame:CGRectMake(0, 0, SCR_W, SCR_H) backColor:RGBA(235, 235, 235, 1.0)];
    _mainView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCR_W, SCR_H)];
    _mainView.backgroundColor = RGBA(235, 235, 235, 1.0);
    [self.view addSubview:_mainView];
    
    
    UILabel * Label1 = [GDFactory creatUILabelWithFrame:CGRectMake(10, 10, 100, 30) text:@"指派人:" textColor:RED textFont:[UIFont systemFontOfSize:16]];
    if (iPhone4) {
        Label1.frame = CGRectMake(10, 10, 100, 10);
    }else{
        
        Label1.frame = CGRectMake(10, 10, 100, 30);
    }
    [_mainView addSubview:Label1];
    
    _view1 = [GDFactory creatUIImageViewWithFrame:CGRectMake(10, CGRectGetMaxY(Label1.frame), SCR_W - 20, SCR_H/13) backgroundImage:@"下拉框_03"];
    if (iPhone4) {
        
        _view1.frame = CGRectMake(10, CGRectGetMaxY(Label1.frame)+ 5 , SCR_W - 20, SCR_H/13);
    }else{
        
        _view1.frame = CGRectMake(10, CGRectGetMaxY(Label1.frame), SCR_W - 20, SCR_H/13);
    }
    //    [_view1.layer setBorderWidth:1.0];
    //    [_view1.layer setBorderColor:RGBA(202, 202, 202, 1.0).CGColor];
    [_mainView addSubview:_view1];
    
    //订单区位
    _roomLabel = [GDFactory creatUILabelWithFrame:CGRectMake(10, 0, _view1.frame.size.width, _view1.frame.size.height) text:@"请选择" textColor:RGBA(164, 164, 164, 1.0) textFont:[UIFont systemFontOfSize:18]];
    _roomLabel.textAlignment = NSTextAlignmentLeft;
    
    // 添加点击手势
    UITapGestureRecognizer * roomGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(roomGseture)];
    _view1.userInteractionEnabled = YES;
    _roomLabel.userInteractionEnabled = YES;
    [_roomLabel addGestureRecognizer:roomGesture];
    
    [_view1 addSubview:_roomLabel];
    
    UILabel * label2 = [GDFactory creatUILabelWithFrame:CGRectMake(10, CGRectGetMaxY(_view1.frame)+10, 300, 30) text:@"订单完成截止时间:" textColor:RED textFont:[UIFont systemFontOfSize:16]];
    [_mainView addSubview:label2];
    
    
    _view2 = [GDFactory creatUIImageViewWithFrame:CGRectMake(10, CGRectGetMaxY(label2.frame), SCR_W - 20, SCR_H/12) backgroundImage:@"下拉框_03"];
    if (iPhone4) {
        _view2.frame = CGRectMake(10, CGRectGetMaxY(label2.frame) + 5, SCR_W - 20, SCR_H/13);
    }else{
        
        _view2.frame = CGRectMake(10, CGRectGetMaxY(label2.frame), SCR_W - 20, SCR_H/13);
    }
    //    [_view2.layer setBorderWidth:1.0];
    //    [_view2.layer setBorderColor:RGBA(202, 202, 202, 1.0).CGColor];
    _view2.userInteractionEnabled = YES;
    [_mainView addSubview:_view2];
    
    // 订单类型
    
    _cateButton = [[UIButton alloc] initWithFrame:CGRectMake(10, 0, _view2.frame.size.width, _view2.frame.size.height)];
    [_cateButton setTitle:@"请选择" forState:UIControlStateNormal];
    [_cateButton setTitleColor:RGBA(164, 164, 164, 1.0) forState:UIControlStateNormal];
    _cateButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    _cateButton.titleLabel.font = [UIFont systemFontOfSize:18];
    
    [_cateButton addTarget:self action:@selector(cateGesture) forControlEvents:UIControlEventTouchUpInside];
    [_view2 addSubview:_cateButton];
    
    
    //  下单按钮
    _grabBtn = [[UIButton alloc] init];
    _grabBtn.frame = CGRectMake(SCR_W/4, CGRectGetMaxY(_view2.frame)+30, SCR_W/2, 40);
    //    if (iPhone4) {
    //        _grabBtn.frame = CGRectMake(0, 0, SCR_W/2, 30);
    //        _grabBtn.center = CGPointMake(SCR_W * 0.5, CGRectGetMaxY(_addImageView.frame)+ 30);
    //    }else{
    //
    //        _grabBtn.frame = CGRectMake(0, 0, SCR_W/2, 40);
    //        _grabBtn.center = CGPointMake(SCR_W * 0.5, CGRectGetMaxY(_addImageView.frame)+ 30);
    //    }
    
    [_grabBtn setBackgroundImage:[UIImage imageNamed:@"3在线下单"] forState:UIControlStateNormal];
    [_grabBtn setTitle:@"确认指派" forState:UIControlStateNormal];
    [_grabBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    _grabBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    [_grabBtn addTarget:self action:@selector(clickGet) forControlEvents:UIControlEventTouchUpInside];
    
    [_mainView addSubview:_grabBtn];
//    _mainView.contentSize = CGSizeMake(SCR_W, CGRectGetMaxY(_grabBtn.frame)+80);
    
}



#pragma mark -- 请求指派人列表数据
- (void)requestWGHData{
    
    [_roomArray removeAllObjects];
    [_cateArray removeAllObjects];
    [_dataArray removeAllObjects];
    
    NSArray * keyArray = @[@"GUID",@"ID",@"SYSCODE"];
    NSArray * valueArray = @[self.OrderGUID,@"",@""];
    NSDictionary * dict = [NSDictionary dictionaryWithObjects:valueArray forKeys:keyArray];
    NSString * urlStr = [NSString stringWithFormat:@"%@%@",Base_URL,ImposeUserInfoList_URL];
    //    [SVProgressHUD showWithStatus:@"加载中..."];
    
    HZNetWorkAgent *agent = [HZNetWorkAgent shareInstance];
    [agent requestUrl:urlStr param:dict baseUrl:@"" withRequestMethod:HZRequestMethodPost withCompletionWithSuccess:^(HZBaseRequest *http, BOOL isSuccess) {
        NSMutableArray * array = [http.returnArray mutableCopy];
        for (NSDictionary * dataDict in array) {
            
            ImposeUserInfoModel * model = [[ImposeUserInfoModel alloc] initWithDict:dataDict];
            [_roomArray addObject:model];
        }
        [_roomTableView reloadData];
        
    } withTag:101];
    
    
}



#pragma mark -- 指派操作
- (void)ImposeOrderDo{
    [_roomTableView reloadData];
    // 获取系统时间
    //    NSDate * date = [NSDate date];
    //    NSTimeZone * zone = [NSTimeZone systemTimeZone];
    //    NSInteger interval = [zone secondsFromGMTForDate: date];
    //    // 获取当前时间
    //    NSDate * localeDate = [date  dateByAddingTimeInterval: interval];
    
    // 取出数据
    NSUserDefaults * roomDefaults = [NSUserDefaults standardUserDefaults];
    NSString * guid = [roomDefaults objectForKey:@"GRID_GUID"];
    NSString * type = [roomDefaults objectForKey:@"TYPE"];
    
    //    NSString * remarkStr = [remark stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString * OBJECT_GUID = @"86d92072-9021-409b-b9db-eb0001c91986";
    
    NSArray * keyArray = @[@"GUID",@"USER_ID",@"USER_CODE",@"dPlanDate",@"TYPE"];
    NSArray * valueArray = @[self.OrderGUID,self.selectedUserId,self.selectedUserCode,self.selectDateStr,@"GET"];
    NSDictionary * dict = [NSDictionary dictionaryWithObjects:valueArray forKeys:keyArray];
    NSString * urlStr = [NSString stringWithFormat:@"%@%@",Base_URL,ImposeOrderDo_URL];
    //    [SVProgressHUD showWithStatus:@"加载中..."];
    
    HZNetWorkAgent *agent = [HZNetWorkAgent shareInstance];
    [agent requestUrl:urlStr param:dict baseUrl:@"" withRequestMethod:HZRequestMethodPost withCompletionWithSuccess:^(HZBaseRequest *http, BOOL isSuccess) {
        NSMutableArray * array = [http.returnArray mutableCopy];
        for (NSDictionary * dataDict in array) {
            _state = [dataDict objectForKey:@"STATUS"];
        }
        
        if ([_state isEqualToString:@"SUCCESS"]) {
            [self.navigationController popToRootViewControllerAnimated:YES];
            
        }else{
            [MBProgressHUD HUDShowMessage:@"指派失败" addedToView:self.view];
        }
        
        
        [_roomTableView reloadData];
    } withTag:101];
}



#pragma mark -- 搭建指派人列表
- (void)buildImposerUserTableView{
    
    if (!_roomTableView) {
        _roomTableView = [[UITableView alloc] init];
        _roomTableView.rowHeight = 30;
        //        _roomTableView.frame = CGRectMake(10, CGRectGetMaxY(_view1.frame), _view1.frame.size.width, SCR_H - CGRectGetMaxY(_view1.frame));
        _roomTableView.frame = CGRectMake(10, CGRectGetMaxY(_view1.frame), _view1.frame.size.width, 150);
        _roomTableView.delegate = self;
        _roomTableView.dataSource = self;
        _roomTableView.tag = 100;
        _roomTableView.tableFooterView = [[UIView alloc] init];
        //    _roomTableView.backgroundColor = [UIColor redColor];
        [_mainView addSubview:_roomTableView];
    }
}

#pragma mark -- 搭建datePicker
- (void)buildDatePicker{
    
    if (!_datePicker) {
        _datePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(10, CGRectGetMaxY(_view2.frame), _view2.frame.size.width, 150)];
        _datePicker.backgroundColor = [UIColor whiteColor];
        _datePicker.date = [NSDate date];
        _datePicker.timeZone = [NSTimeZone timeZoneWithName:@"GTM+8"];
        _datePicker.minimumDate = [NSDate dateWithTimeIntervalSinceNow:24*60*60];
        _datePicker.datePickerMode = UIDatePickerModeDateAndTime;
        [_datePicker addTarget:self action:@selector(datePickerValueChanged:) forControlEvents:UIControlEventValueChanged];
        [_mainView addSubview:_datePicker];
        
        NSDate *defaultDate = [NSDate dateWithTimeIntervalSinceNow:24*60*60];
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm";
        self.selectDateStr = [dateFormatter stringFromDate:defaultDate];
        [_cateButton setTitle:self.selectDateStr forState:UIControlStateNormal];
    }
}

- (void)datePickerValueChanged:(UIDatePicker *)sender {
    NSDate *selectDate = [sender date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm";
    self.selectDateStr = [dateFormatter stringFromDate:selectDate];
    [_cateButton setTitle:self.selectDateStr forState:UIControlStateNormal];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (tableView.tag == 100) {
        return _roomArray.count;
    }
    else{
        
        return _cateArray.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSString * ID = @"GD";
    if (tableView.tag == 100) {
        UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:ID];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
        }
        ImposeUserInfoModel * roomModel = _roomArray[indexPath.row];
        cell.textLabel.text = roomModel.USER_NAME;
        cell.textLabel.font = [UIFont systemFontOfSize:16];
        return cell;
    }else{
        
        UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:ID];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
        }
        GetWGHModel * cateModel = _cateArray[indexPath.row];
        cell.textLabel.text = cateModel.TEXT;
        cell.textLabel.font = [UIFont systemFontOfSize:16];
        return cell;
    }
    
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [_roomTableView removeFromSuperview];
    _roomTableView = nil;
//    [_cateTableView removeFromSuperview];
//    _cateTableView = nil;
    roomShow = NO;
    cateShow = NO;
    NSUserDefaults * roomDefaults = [NSUserDefaults standardUserDefaults];
    
    if (tableView.tag == 100) {
        
        ImposeUserInfoModel * roomModel = _roomArray[indexPath.row];
        _roomLabel.text = roomModel.USER_NAME;
        _selectedUserId = roomModel.USER_Id;
        _selectedUserCode = roomModel.USER_Code;
        
        // 保存数据
        
//        NSString * guid = roomModel.GUID;
//        
//        [roomDefaults setObject:guid forKey:@"GRID_GUID"];
        
    }
    if (tableView.tag == 101) {
        
        GetWGHModel * cateModel = _cateArray[indexPath.row];
        [_cateButton setTitle:cateModel.TEXT forState:UIControlStateNormal];
        
        // 保存数据
        NSString * type = cateModel.GUID;
        [roomDefaults setObject:type forKey:@"TYPE"];
        //        NSString * str = [roomDefaults objectForKey:@"TYPE"];
        //        NSLog(@"%@",str);
        
    }
    
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
    
    [_datePicker removeFromSuperview];
    _datePicker = nil;
    [_roomTableView removeFromSuperview];
    _roomTableView = nil;
    roomShow = NO;
    cateShow = NO;

}



#pragma mark -- 点击指派
- (void)clickGet{
    if ([_roomLabel.text isEqualToString:@"请选择"]) {
        [MBProgressHUD HUDShowMessage:@"请选择指派人" addedToView:self.view];
        return;
    }
    if ([_cateButton.titleLabel.text isEqualToString:@"请选择"]) {
        [MBProgressHUD HUDShowMessage:@"请选择完成时间" addedToView:self.view];
        return;
    }
    [self alertError:@"确认指派？"];
    
}

#pragma mark - 弹框提示
- (void)alertError:(NSString *)error{
    
    // 1.弹框
    UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"提示" message:error delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alert show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if (buttonIndex == 1) {
        [self ImposeOrderDo];
        
    }
}

#pragma mark -- 点击指派人
- (void)roomGseture{
    if (!roomShow) {
        [self buildImposerUserTableView];
    } else {
        [_roomTableView removeFromSuperview];
        _roomTableView = nil;
    }
    roomShow = !roomShow;
}

#pragma mark --- 点击完成时间
- (void)cateGesture{
    if (!cateShow) {
        [self buildDatePicker];
    } else {
        [_datePicker removeFromSuperview];
        _datePicker = nil;
    }
    cateShow = !cateShow;
}

- (void)clickLeft {
    [self.navigationController popViewControllerAnimated:YES];
}

@end
